//
// Created by lenovo on 25-1-31.
//
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    static vector<vector<int>> levelOrderBottom(TreeNode* root)
    {
        vector<vector<int>> vv;
        queue<TreeNode*> q;
        int levelSize = 0;

        if(root)
        {
            q.push(root);
            levelSize = 1;
        }

        while(!q.empty())
        {
            vector<int> v;
            for(int i=0; i<levelSize; i++)
            {
                TreeNode* front = q.front();
                v.push_back(front->val);
                q.pop();

                if(front->left)
                    q.push(front->left);
                if(front->right)
                    q.push(front->right);

            }
            levelSize = q.size();
            vv.push_back(v);
        }

        reverse(vv.begin(), vv.end());
        return vv;
    }
};